package com.softjourn.punchcard.lib;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.softjourn.punchcard.R;

public class Coder extends AsyncTask<String, Integer, ImageView> {

	private Activity act;
	private ProgressDialog dialog;
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
	private static final int ID = 34646456;

	public Coder(Activity act) {
		this.act = act;
	}

	@Override
	protected void onPreExecute() {
		dialog = new ProgressDialog(act);
		dialog.setTitle("Encoding");
		dialog.setMessage("Please, wait...");
		dialog.setCancelable(false);
		dialog.show();
		super.onPreExecute();
	}

	@Override
	protected ImageView doInBackground(String... params) {
		DisplayMetrics dm = new DisplayMetrics();
		act.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;
		ImageView image = new ImageView(act);

		Bitmap bitmap = getImage(params[0]);
		if (bitmap == null) {

			try {
				BitMatrix matrix = new QRCodeWriter().encode(params[0],
						com.google.zxing.BarcodeFormat.QR_CODE, width, width);
				bitmap = matrixToBitmap(matrix);

				savaImage(bitmap, params[0]);

			} catch (WriterException e) {
				e.printStackTrace();
			}
		}
		image.setImageBitmap(bitmap);

		image.setId(ID);
		return image;
	}

	@Override
	protected void onPostExecute(ImageView image) {
		try {
			dialog.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}
		ImageView old = (ImageView) act.findViewById(ID);
		if (old != null) {
			((FrameLayout) old.getParent()).removeViewInLayout(old);
		}
		
		LinearLayout qrCodeWrapper = (LinearLayout) act
				.findViewById(R.id.qr_code);

		qrCodeWrapper.addView(image);
	
		super.onPostExecute(image);
	}

	private Bitmap matrixToBitmap(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		Bitmap image = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setPixel(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}

	private void savaImage(Bitmap bitmap, String fileName) {

		ByteArrayOutputStream bytes = new ByteArrayOutputStream();

		bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

		File dir = new File(Environment.getExternalStorageDirectory(), "pc");
		if (!dir.exists()) {
			if (dir.mkdir()) {
				try {

					// you can create a new file name "test.jpg" in sdcard
					// folder.
					File f = new File(dir + File.separator + fileName + ".jpg");
					f.createNewFile();
					// write the bytes in file
					FileOutputStream fo = new FileOutputStream(f);
					fo.write(bytes.toByteArray());

					// remember close the FileOutput
					fo.close();
					// Save image into your new created album gallery
					MediaStore.Images.Media.insertImage(
							act.getContentResolver(), f.getAbsolutePath(),
							fileName, "Description");
					// Increment the picNumber variable that construct the
					// picture name for the next created/taken picture

				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

				}
			}
		}
	}

	private Bitmap getImage(String fileName) {

		File dir = new File(Environment.getExternalStorageDirectory(), "pc");
		File f = new File(dir + File.separator + fileName + ".jpg");

		try {
			return MediaStore.Images.Media.getBitmap(act.getContentResolver(),
					Uri.fromFile(f));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}